#!/usr/bin/perl 
use warnings;
use strict;
use List::Util qw(minstr sum min shuffle);

my $usage="\nusage: ./convert-output-to-sorted.pl  output-1.txt\n" .
          "\nConverts your knapsack output to a sorted format ready to diff with my correct output\n" .
          "Step #1) run your knapsack program and redirect its output into a text file:\n\t./a.out input-1.txt > myoutput-1.txt\n" .
          "Step #2) run this PERL script as follows:\n\t./convert-output-to-sorted.pl myoutput-1.txt\n" .
          "Step #3) look for the new file named sorted-myoutput-1.txt to appear in the same dir.\n" .
          "Step #4) do a   diff -a -b sorted-output-1.txt correct-sorted-output-1.txt\n" .
          "Step #5) if there are no diffs then your program is correct for this particular input file\n";
          
die( "$usage") if (scalar(@ARGV)<1);
my $infil = shift;
open(INFIL,"<$infil" ) || die( "Can't open $infil for read\n");

my $setLine = <INFIL>;
my $target = <INFIL>;
my @lines = <INFIL>; # GULP the rest of the lines - each line is a solution subset;
close (INFIL);

open (OUTFIL, ">sorted-" ."$infil" ) || die ("Can't open for write: " . "sorted-" . "$infil" );
my @set = split (' ', $setLine );
$setLine = join( ' ', @set );
print OUTFIL "@set\n$target";

my %subsets;
my @subsets;
foreach my $line (@lines)
{
	my @subset = split( ' ', $line );
	@subset = sort { $a <=> $b } @subset;
	$line = join( ' ', @subset );
	$subsets{$line}=$line;
	push (@subsets, $line);
}
@subsets = sort @subsets;
foreach my $line (@subsets)
{
	print OUTFIL "$line\n";
}
close(OUTFIL);
